﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="VmMilestones.cs" company="Mar3ek">
//   http://mar3ek.wordpress.com
// </copyright>
// <summary>
//   
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Mar3ek.HouseLight
{
    using System;
    using System.Collections.ObjectModel;
    using System.ComponentModel;
    using System.Threading;
    using System.Windows;
    using System.Windows.Input;
    using LighthouseNET;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public partial class ToolWindowViewModel
    {
        private readonly ICommand _newMilestoneCommand;
        private readonly ICommand _modifyMilestoneCommand;
        private readonly ICommand _deleteMilestoneCommand;
        private readonly ICommand _showMilestoneTicketsCommand;
        private readonly ICommand _showMilestoneOpenTicketsCommand;
        private bool _isMilestonesEnabled = true;
        private ObservableCollection<Milestone> _milestones;
        private Milestone _selectedMilestone;

        /// <summary>
        /// Gets or sets the milestones.
        /// </summary>
        /// <value>
        /// The milestones.
        /// </value>
        public ObservableCollection<Milestone> Milestones
        {
            get
            {
                return _milestones;
            }

            set
            {
                _milestones = value;
                OnPropertyChanged(new PropertyChangedEventArgs("Milestones"));
            }
        }

        /// <summary>
        /// Gets or sets the selected milestone.
        /// </summary>
        /// <value>
        /// The selected milestone.
        /// </value>
        public Milestone SelectedMilestone
        {
            get
            {
                return _selectedMilestone;
            }

            set
            {
                _selectedMilestone = value;
                OnPropertyChanged(new PropertyChangedEventArgs("SelectedMilestone"));
            }
        }

        /// <summary>
        /// Gets the new milestone command.
        /// </summary>
        public ICommand NewMilestoneCommand
        {
            get { return _newMilestoneCommand; }
        }

        /// <summary>
        /// Gets the modify milestone command.
        /// </summary>
        public ICommand ModifyMilestoneCommand
        {
            get { return _modifyMilestoneCommand; }
        }

        /// <summary>
        /// Gets the delete milestone command.
        /// </summary>
        public ICommand DeleteMilestoneCommand
        {
            get { return _deleteMilestoneCommand; }
        }

        /// <summary>
        /// Gets the show milestone tickets command.
        /// </summary>
        public ICommand ShowMilestoneTicketsCommand
        {
            get { return _showMilestoneTicketsCommand; }
        }

        /// <summary>
        /// Gets the show milestone open tickets command.
        /// </summary>
        public ICommand ShowMilestoneOpenTicketsCommand
        {
            get { return _showMilestoneOpenTicketsCommand; }
        }

        /// <summary>
        /// Gets or sets a value indicating whether this instance is milestones enabled.
        /// </summary>
        /// <value>
        /// <c>true</c> if this instance is milestones enabled; otherwise, <c>false</c>.
        /// </value>
        public bool IsMilestonesEnabled
        {
            get
            {
                return _isMilestonesEnabled;
            }

            set
            {
                _isMilestonesEnabled = value;
                OnPropertyChanged(new PropertyChangedEventArgs("IsMilestonesEnabled"));
            }
        }

        /// <summary>
        /// Gets the project milestones
        /// </summary>
        private void RefreshMilestones()
        {
            var t = new Thread(() =>
            {
                try
                {
                    Milestones = new ObservableCollection<Milestone>(_api.GetMilestones(_selectedProject.Id));
                }
                catch (Exception)
                {
                    IsMilestonesEnabled = false;
                }
            }) { IsBackground = true, Name = "Refresh milestones thread" };
            t.Start();
        }

        /// <summary>
        /// Deletes the specified milestone.
        /// </summary>
        /// <param name="parameter">The parameter.</param>
        private void DeleteMilestoneAction(object parameter)
        {
            if (parameter == null)
            {
                return;
            }

            var milestone = (Milestone)parameter;

            var result = MessageBox.Show(
                "Do you really want to delete the selected milestone? This action cannot be undone.",
                "HouseLight",
                MessageBoxButton.YesNo,
                MessageBoxImage.Question);

            if (result != MessageBoxResult.Yes)
            {
                return;
            }

            try
            {
                _api.DeleteMilestone(SelectedProject.Id, milestone.Id);
                RefreshMilestones();
            }
            catch (LighthouseResponseException ex)
            {
                MessageBox.Show(
                    ex.Message,
                    "HouseLight",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
            }
            catch (LighthouseServerException ex)
            {
                MessageBox.Show(
                    string.Format("A communication error was encountered. Check your internet connection and try again.\nIf the problem persists, contact the plugin developer.\nError details follow:\n\n{0}", ex.Message),
                    "HouseLight",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// Displays the modify milestone window
        /// </summary>
        /// <param name="parameter">The parameter.</param>
        private void ModifyMilestoneAction(object parameter)
        {
            if (parameter == null)
            {
                return;
            }

            var w = new wNewMilestone(_api, (Milestone)parameter) { Owner = _mainWindow };
            w.Closed += MilestoneWindowClosed;
            w.Show();
        }

        /// <summary>
        /// Handles the Closed event of a wNewMilestone window
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void MilestoneWindowClosed(object sender, EventArgs e)
        {
            if (((wNewMilestone)sender).Result)
            {
                RefreshMilestones();
            }
        }

        /// <summary>
        /// Displays the new milestone window
        /// </summary>
        /// <param name="parameter">The parameter.</param>
        private void NewMilestoneAction(object parameter)
        {
            if (parameter == null)
            {
                return;
            }

            var w = new wNewMilestone(_api, ((Project)parameter).Id) { Owner = _mainWindow };
            w.Closed += MilestoneWindowClosed;
            w.Show();
        }

        /// <summary>
        /// Filters the tickets belonging to current milestone
        /// </summary>
        /// <param name="parameter">The parameter.</param>
        private void ShowMilestoneOpenTicketsAction(object parameter)
        {
            if (parameter == null)
            {
                return;
            }

            SelectedTabIndex = 0;
            FilterKeyword = string.Format("milestone:\"{0}\" state:open", ((Milestone)parameter).Title);
            FilterAction(_filterKeyword);
        }

        /// <summary>
        /// Filters the open tickets belonging to current milestone
        /// </summary>
        /// <param name="parameter">The parameter.</param>
        private void ShowMilestoneTicketsAction(object parameter)
        {
            if (parameter == null)
            {
                return;
            }

            SelectedTabIndex = 0;
            FilterKeyword = string.Format("milestone:\"{0}\"", ((Milestone)parameter).Title);
            FilterAction(_filterKeyword);
        }
    }
}
